package cn.sunlelin.educationserver.interceptor;

import cn.sunlelin.educationserver.util.JWTUtil;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.google.gson.Gson;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception {
//此句代码不能删除。如果删除，有些前端发出的请求会被拦截了。有时别除这段代码，会运行正确：有时删除这段代码，不会运行正确。
        if (!(handler instanceof HandlerMethod)) {//当前处理请求的对象不是方法
            return true;//放行
        }
        String token = request.getHeader("token");
        String userIdt=request.getHeader("userId");
        System.out.println("LoginInterceptor token=" + token+userIdt);

        Map<String, Object> map = new HashMap<>();
        if (token == null || token == "" || "null".equals(token)) {
            map.put("code", 4010);
            map.put("msg", "未登录");
            String jsonstring = new Gson().toJson(map);//将对象转化为json格式
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(jsonstring);
            return false;//拦截
        }

        try {
            DecodedJWT t=JWTUtil.verifyToken(token);
            String userId=t.getClaim("userId").asString();
            //核对userId是否正确
            if(!userId.equals(userIdt)){
                map.put("code",5010);
                map.put("msg","签名不正确");
            }else {
                return true;//放行
            }
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            map.put("code", 4000);
            map.put("msg", "签名不正确");
        } catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            map.put("code", 4000);
            map.put("msg", "签名算法不正确");
        } catch (TokenExpiredException e) {
            e.printStackTrace();
            map.put("code", 4000);
            map.put("msg", "token过期了");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code", 4000);
            map.put("msg", "发生异常");
        }
        String jsonstring = new Gson().toJson(map);
        response.setContentType("application/json;charset=Utf-8");//将对象转化为json格式
        response.getWriter().write(jsonstring);
        return false;//拦截
    }
}